package com.jee.ssm.common.utils;

import com.jee.ssm.common.config.Logger;
import com.jee.ssm.modules.smRecord.services.SmRecordService;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
public class SmUtils {

    private String username = "jnytxx";//这里设置帐号
    private String passwd = "071026*";//这里设置密码

    private String address = "http://www.qybor.com/qyb/view/crm/login.jsp";//短信管理地址

    public void sendMsg(String id, String phone,String msg,String username,String passwd,String needstatus,String port,String sendtime) throws IOException {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);//设置连接超时时间为2秒（连接初始化时间）
        PostMethod post = new PostMethod("http://www.qybor.com:8500/shortMessage");
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
        NameValuePair[] data ={
                new NameValuePair("username",username),
                new NameValuePair("passwd",passwd),
                new NameValuePair("phone",phone),
                new NameValuePair("msg",msg),
                new NameValuePair("needstatus",needstatus),
                new NameValuePair("port",port),
                new NameValuePair("sendtime",sendtime)
        };
        post.setRequestBody(data);
        client.executeMethod(post);
        int statusCode = post.getStatusCode();
        System.out.println(new String(post.getResponseBodyAsString().getBytes()));
        if(statusCode == 200) {
            try {
                smRecordService.updateSuccessById(id);
            } catch (Exception e) {
                Logger.error("短信发送成功，但是修改状态失败");
            }
        }
        post.releaseConnection();
    }
    /**
     * 简单短信发送
     * @param phone 手机号码，多个
     * @param msg 短信内容
     * @throws Exception
     */
    public void send(String id, String phone, String msg) {

        new Thread(() -> {
            try {
                sendMsg(id, phone, msg, this.username, this.passwd, "true", "", "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

    }

    @Resource
    private SmRecordService smRecordService;

}
